﻿#region

using System.IO;
using System.Text;
using System.Xml.Serialization;

#endregion

namespace Framework.Text.SerializerProvider
{
    /// <summary>
    ///   xml 序列化器
    /// </summary>
    /// <typeparam name = "T"></typeparam>
    public class XmlSerializerProvider<T> : ISerializer<T>
    {
        private readonly XmlSerializer _xmlSerializer = new XmlSerializer(typeof (T));

        #region ISerializer<T> Members

        public string Serialize(T obj)
        {
            using (var writer = new Utf8Writer())
            {
                _xmlSerializer.Serialize(writer, obj);
                return writer.ToString();
            }
        }

        public T Deserialize(string input)
        {
            return (T) _xmlSerializer.Deserialize(new StringReader(input));
        }

        #endregion

        #region Nested type: Utf8Writer

        private sealed class Utf8Writer : StringWriter
        {
            public override Encoding Encoding
            {
                get { return Encoding.UTF8; }
            }
        }

        #endregion
    }
}